package com.daykw.xiaohongshu.util;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.framework.state.ConnectionStateListener;
import org.apache.log4j.Logger;
import org.apache.zookeeper.CreateMode;

public class MyConnectionStateListener implements ConnectionStateListener {
	private static Logger logger = Logger.getLogger(MyConnectionStateListener.class);
	private String path;
	private String content;

	public MyConnectionStateListener(String path, String content) {
		this.path = path;
		this.content = content;
	}

	@Override
	public void stateChanged(CuratorFramework curatorFramework, ConnectionState connectionState) {
		if (connectionState == ConnectionState.LOST) {
			for (int i = 0; i < 5; i++) {
				try {
					if (curatorFramework.getZookeeperClient().blockUntilConnectedOrTimedOut()) {
						curatorFramework.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path,
								content.getBytes("UTF-8"));
						break;
					}
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					logger.error("", e);
					break;
				} catch (Exception e) {
					logger.error("", e);
				}
			}
		}
	}
}
